<template>
  <section>
    <!-- 这个页面是定制版的分组界面 -->
    <el-col :span="5" style="margin-top: 15px;">
      <div class="section-content clearfix">
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;margin:0;">
          <el-form :inline="true">
            <el-form-item>
              <el-button  type="primary" plain  @click="handleAdd">添加分组</el-button>
            </el-form-item>
              <el-form-item style="padding-left:20px;">
              <el-button  type="primary" plain  @click="rendbool=!rendbool">编辑分组</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <div style="clear: both;"></div>
        <div style="width:100%;background-color:#0099cc;padding:10px 5px 5px;color:#fff;">设备分组</div>
        <el-tree
          @node-click="getlists"
          :data="query"
          :props="defaultProps"
          node-key="id"
          :default-expanded-keys="[openGroup]"
          :expand-on-click-node="false"
          :render-content="renderContent"
        ></el-tree>
      </div>
    </el-col>

    <el-col :span="18">
      <div class="section-content clearfix">
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
          <!-- <el-form>
            <el-form-item style="text-align: right">
              <span style="float:left;font-weight:bold;">{{textname}}</span>
              <el-button type="primary" v-on:click="addshow()">添加设备</el-button>
            </el-form-item>
          </el-form> -->
          <div class="group-title">
              <div v-if="runModelist">
                <span>原始模式</span>  
                <el-switch v-model="devicemodelgroup" :active-value="1" :inactive-value='0'  @change="devicegroup" active-color="#13ce66"></el-switch>
                <span>优化模式</span>   
              </div>
              <div style="background: #0099cc;padding: 0 20px;color: #fff;">{{textname}}</div>
              <div>
                <el-select v-model="devicerecipeId" @change="getlist">
                   <el-option v-for="item in devicerecipe" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </div>
              <el-button type="primary" v-on:click="addshow()">添加设备</el-button>
              <div>{{moment}}</div>
            </div>
          <!-- 列表 -->
          <el-table
            id="devicetable"
            v-if="deviceQuery!=''"
            :data="deviceQuery"
            border
            highlight-current-row
            v-loading="listLoading"
            @selection-change="selsChange"
            style="width: 100%;"
          >
            <!-- style="width: 100%;height: 275px;overflow: auto;" -->
            <el-table-column width="150" label="从机设备"  align="center">
              <template scope="scope">
                <!-- <span class="pb-name" @click="details(scope.$index, scope.row)"> -->
                <span :title="scope.row.name">
                  {{scope.row.deviceSlave.name}}
                </span>
              </template>
            </el-table-column>
            <el-table-column width="150" align="center" v-for="(item, index) in deviceQuery[0].deviceRecipeBodyVos" :label="item.name" >
              <template scope="scope">{{scope.row.deviceRecipeBodyVos[index].registerVal}}</template>
            </el-table-column>
            <!-- <el-table-column align="center" prop="" label="环境温度℃" ></el-table-column>
            <el-table-column align="center" prop="" label="回风温度℃" >
              <template scope="scope">{{scope.row.deviceTypeName}}</template>
            </el-table-column>
            <el-table-column align="center" prop="" label="运行电源A" width='200'></el-table-column>           
            <el-table-column align="center" prop="" label="运行电阻V" width='200'></el-table-column>           
            <el-table-column align="center" prop="" label="当前电能Kwh" width='200'></el-table-column>           
            <el-table-column align="center" label="操作">
              <template scope="scope">
                <i
                  @click="handleDel(scope.$index, scope.row)"
                  icon="el-icon-delete"
                  circle
                  title="删除"
                  class="pb-icon icon-delete"
                ></i>
              </template>
            </el-table-column> -->
          </el-table>
        </el-col>
         <el-col :span="24" class="toolbar">
          
        <!-- <el-button type="danger"  @click="alarmVisible=true"  :disabled="this.sels.length===0" >批量修改告警开关</el-button> -->
           <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total"
                style="float:right;">
            </el-pagination>
        </el-col>
      </div>
      <div style="position: relative;padding-left:80px;" v-if="deviceQuery!=''">
        <!-- 选择模式 -->
          <div class="parameter" v-if="runModelist" style="top:-30px;left:170px;">
          <!-- <div class="parameter"  style="top:-30px;left:170px;"> -->
            <span>原始模式</span>  
                <el-switch v-model="devicemodel"  :active-value="1" :inactive-value='0'  @change="changedevicemodel" active-color="#13ce66"></el-switch>
            <span>优化模式</span>
          </div>
         <!-- 模式 -->
          <div class="parameter" v-if="oriModelist" style="top:-30px;right:200px;">
            <span>模式：</span>  
            <span v-if="orimodel==0" class="color-blue">原模式</span>
            <span v-if="orimodel==1" class="color-blue">优化模式</span>
          </div>
           <!-- 回风温度 -->
          <div v-if="backTmplist" class="parameter" style="bottom:-30px;left:200px;">
            <span>{{backTmplist.name}}：</span>  
            <span v-if="backTmplist.registerVal" class="color-blue" :title="backTmplist.registerVal+backTmplist.unit">{{backTmplist.registerVal}}{{backTmplist.unit}}</span>
          </div>
           <!-- 当前能耗 -->
          <div v-if="curEnerglist" class="parameter" style="bottom:-30px;right:200px;flex-wrap: wrap;text-align:center;">
            <div style="padding:0 8px;width:100%">{{curEnerglist.name}}：</div>  
            <div style="white-space:nowrap;overflow:hidden;" :title="curEnerglist.registerVal+curEnerglist.unit" v-if="curEnerglist.registerVal" class="color-blue">{{curEnerglist.registerVal}}{{curEnerglist.unit}}</div>
          </div>
          <!-- 侧边的列表 -->
          <div :class="deviceQuery.length>4? 'device-formula-list device-formula-list2':'device-formula-list'" :style="{width:devicewidth,background:devicebackground}">
            <div :class="deviceIndex==index ?'devicetitle bg-wihte':'devicetitle'" @click="changedevice(index)" v-for="(item,index) in deviceQuery" :title="item.name+'-'+item.deviceSlave.name">{{item.deviceSlave.name}}</div>
          </div>
          <div v-if="deviceQuery.length>8" class="loadmroe" @click="showalldevice">......</div>
          <div v-if="hidedevice" class="loadmroe" @click="hidelldevice"><<</div>
          <div style="width: 95%;overflow;hidden;border: 2px solid #0099cc;border-radius: 60px;z-index:1;padding:40px 25px;">
          <div class="col-bg">
          <el-row :gutter="10">
              <el-col :lg="12" :md="24" v-for="(item,index) in hande_device_list" style="padding: 5px;">
                  <div style="background: #eee;padding: 5px 0 0 10px;" class="clearfix">
                      <el-col :xs="12" :sm="6">
                          <div :title="item.name" style="color: #000;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">{{item.name}}</div>
                          <div  style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">数据点地址:{{item.register}}</div>
                      </el-col>
                      <el-col :xs="12" :sm="2" style="text-align: left;">
                          <!-- <div v-if="facility.state==1"> -->
                          <div style="min-height:44px;">
                              <div style="color: #000">状态</div>
                              <span v-if="item.communicateState==0" class="pb-colorbg bg-green"
                                  title="正常"></span>
                              <span v-if="item.communicateState==1" class="pb-colorbg bg-red"
                                  title="故障"></span>
                              <span v-if="item.communicateState==null" class="pb-colorbg bg-gray"
                                  title="未知"></span>
                          </div>
                          <!-- <div v-else>
                              <span class="pb-colorbg bg-gray" title="离线"></span>
                          </div> -->
                      </el-col> 
                      <el-col :xs="12" :sm="4">
                          {{item.updateTime}}
                      </el-col>

                      <el-col :xs="12" :sm="6" style="">
                          <div v-if="item.dataType==1  ">
                              <el-tooltip style="height:42px;" v-if="item.registerVal==0||item.registerVal==1" :content="'开关'">
                                  <el-switch :disabled="item.writeRead==0||menubt.indexOf('/device/cmd')==-1" @change="scade1(index, item)" v-model="item.registerVal"
                                      active-value="1" inactive-value="0">
                                  </el-switch>
                                      <!-- :disabled="item.writeRead==0||menubt.indexOf('/device/cmd')==-1" -->
                              </el-tooltip>
                              <div v-else>无效</div>
                          </div>
                          <span v-if="item.dataType!=1" style="display: block;max-height:42px;overflow: hidden;">
                              <div>当前值：</div>
                              
                              <span style="font-size:16px;font-weight: bold;overflow:hidden;">{{item.registerVal}}</span>
                              <span v-if="item.unit">({{item.unit}})</span>
                              
                          </span>
                      </el-col>
                      
                       <el-col :xs="12" :sm="6">
                        <span
                            v-if="item.writeRead==1 && item.dataType!=1&&menubt.indexOf('/device/cmd')>-1">
                            <i title="写数据点值" @click="fromedit(index,item)" type="warning"
                                class="pb-icon icon-bianji"></i>
                        </span>
                        <span v-else>
                            <i title="禁止使用" type="warning" class="pb-icon icon-bianjino"></i>
                        </span>
                        <i v-if="menubt.indexOf('/devices/histor')>-1" @click="handlehisty(index, item)"
                            title="历史查询" circle class="pb-icon icon-lishi"></i>
                        <i v-if="menubt.indexOf('/device/cmd')>-1" @click="scade2(index, item)" circle
                            title="主动采集" class="pb-icon icon-caiji"></i>
                    </el-col>
                  </div>
              </el-col>
          </el-row>
          </div>
          </div>
      </div>
    </el-col>
    <el-dialog
      title="编辑"
      v-show="editFormVisible"
      v-model="editFormVisible"
      @close="editFormVisible=false"
    >
      <div slot="footer" style="text-align: left; ">
        <el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
          <el-form-item label="分组名称" prop="name">
            <el-input v-model="editForm.name" auto-complete="off"></el-input>
          </el-form-item>

          <el-form-item label="所属分组">
            <el-select v-model="editForm.parentId" placeholder="请选择">
              <el-option
                v-for="item in querys"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                v-if="editshow!=item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="排序值">
            <el-input v-model="editForm.priority" type="number"></el-input>
          </el-form-item>

          <el-form-item label="分组描述">
            <el-input type="textarea" v-model="editForm.remark"></el-input>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align:right;">
          <el-button @click.native="editFormVisible = false">取消</el-button>
          <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 绑定设备 -->
    <el-dialog
      title="设备绑定"
      v-show="deviceVisible"
      v-model="deviceVisible"
      @close="deviceVisible=false"
    >
      <div slot="footer" style="text-align: left; ">
        <div class="section-content pb-top clearfix">
          <el-col :span="24" class="toolbar">
            <el-form :inline="true" :model="filters" @submit.native.prevent>
              <div>
                <el-form-item>
                  <el-input
                    v-model="filters.name"
                    placeholder="设备名称"
                    @keyup.enter.native="getUsers2()"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-input
                    v-model="filters.deviceSn"
                    placeholder="网关SN"
                    @keyup.enter.native="getUsers2()"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-select
                    v-model="filters.deviceTypeId"
                    filterable
                    placeholder="设备类型"
                    @change="getUsers2()"
                  >
                    <el-option label="全选" value=" "></el-option>
                    <el-option
                      v-for="item in typelist"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <!-- <el-form-item>
                  <el-select
                    v-model="filters.terminalUser"
                    placeholder="终端用户"
                    @change="getUsers2()"
                  >
                    <el-option key=" " label="全选" value=" "></el-option>
                    <el-option v-for="item in terminal_list" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item> -->
                <el-form-item>
                  <el-button type="primary" v-on:click="getUsers2">查询</el-button>
                </el-form-item>
              </div>
              <el-form-item label="分组设备">
                <el-transfer
                  :titles="['可选', '已选']"
                  :button-texts="['到左边', '到右边']"
                  v-model="binddata"
                  :data="datalist"
                  @change="handleChange"
                  style="padding-left:30px;padding-bottom:20px;"
                ></el-transfer>
              </el-form-item>
            </el-form>
          </el-col>
        </div>
        <div slot="footer" class="dialog-footer" style="text-align:right;">
          <el-button @click.native="deviceVisible = false">取消</el-button>
          <el-button type="primary" @click.native="deviceSb" :loading="editLoading">提交</el-button>
        </div>
      </div>
    </el-dialog>
    <!--新增界面-->
    <el-dialog
      title="新增"
      v-show="addFormVisible"
      v-model="addFormVisible"
      @close="addFormVisible=false"
    >
      <div slot="footer" style="text-align: left; ">
        <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
          <el-form-item label="分组名称" prop="name">
            <el-input v-model="addForm.name" auto-complete="off"></el-input>
          </el-form-item>

          <el-form-item label="所属分组">
            <el-select v-model="addForm.parentId" placeholder="请选择">
              <el-option v-for="item in querys" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="排序值">
            <el-input v-model="addForm.priority" type="number"></el-input>
          </el-form-item>

          <el-form-item label="分组描述">
            <el-input type="textarea" v-model="addForm.remark"></el-input>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button @click.native="addFormVisible = false">取消</el-button>
          <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 编辑界面 -->
    <el-dialog title="编辑" v-show="editRegisterVisible" v-model="editRegisterVisible" @close="editRegisterVisible=false">
        <div slot="footer" style="text-align: left; ">
            <el-form  label-width="100px">
                <el-form-item label="数据点值" prop="name">
                    <el-input v-model="value2" type="number" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align:right;">
                <el-button @click.native="editRegisterVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editRegisterSubmit" v-loading="listLoading">提交</el-button>
            </div>
        </div>
    </el-dialog>

    <el-dialog  title="编辑"  v-show="alarmVisible" v-model="alarmVisible" @close="alarmVisible=false" >
      <div slot="footer" style="text-align: left; ">
        <el-form  @submit.native.prevent  :model="editForm" label-width="120px" :rules="editFormRules"  ref="editForm">
          <el-form-item label="批量告警状态">
            <el-select v-model="alarmbool" placeholder="批量告警状态">
              <el-option  label="关" value="0"></el-option>
              <el-option  label="开" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align:center;">
          <el-button @click.native="alarmVisible = false">取消</el-button>
          <el-button type="primary" @click.native="alarmSubmit" :loading="editLoading">提交</el-button>
        </div>
      </div>
    </el-dialog>
  </section>
</template>
<script>
// import util from './../common/js/util'
//import NProgress from 'nprogress'
import {
  device_query,
  device_group_query,
  device_group_post,
  device_group_put,
  device_group_delete,
  device_company_group_query,
  device_company_group_add,
  device_company_group_delete,
  user_query,
  device_device_alarm,
  device_device_alarm_list,
  device_company_group_query_slave,
  device_data_recipe_query,
  terminal_user_query,
  device_type_query,
  device_cmd
} from "../../api/api";

export default {
  data() {
    return {
      devicewidth:'',
      devicebackground:'',
      hidedevice: false,
      deviceIndex: 0,
      hande_device_list: [],
      devicerecipeId:'',
      devicerecipe:'',
      momenttime:'',
      moment:'',
      devicemodel: '',
      orimodel:'',
      devicemodelgroup:'',//群控
      userclist: "",
      deviceQuery: "", //分组设备列表
      terminal_list: "",
      typelist: "",
      alarmbool:'0',
      defaultProps: {
        children: "childrens",
        label: "name"
      },
      filters: {
        name: "",
        deviceSn: "",
        deviceTypeId: ""
      },
      scade1s: "",
      scades: "",
      query: [],
      querys: [{ id: 0, name: "默认" }],
      total: 0,
      page: 1,
      listLoading: false,
      sels: [], //列表选中列
      deviceVisible: false, //设备绑定界面显示
      editFormVisible: false, //编辑界面是否显示
      editLoading: false,
      alarmVisible:false,
      editFormRules: {
        name: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur"
          },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ]
      },
      editshow: "",
      //编辑界面数据
      editForm: {
        id: "",
        name: "",
        parentId: "",
        priority: "",
        remark: ""
      },
      refresh:'',
      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur"
          },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        path: [
          {
            required: true,
            message: "请输入path",
            trigger: "blur"
          }
        ]
      },
      openGroup:"",
      //新增界面数据
      addForm: {
        name: "",
        parentId: "",
        priority: "",
        remark: ""
      },
      datalist: [], //数据源
      binddata: [], //绑定的数据,
      deviceGroupId: "", //选择的分组ID,
      rendbool:false,
      textname:'',//当前点击的组名
      pageNo: 1,
      pageSize: 10,
      runModelist:'',
      oriModelist:'',
      devicemsg:'',
      backTmplist:'',//回风温度
      curEnerglist:'',//耗能
      editRegisterVisible: false,
      value2:'',
      editRegisterForm:''
    };
  },
  methods: {
    editRegisterSubmit(){
      this.$confirm('确认提交吗？', '提示', {}).then(() => {
        let para = {
            code: 'writeRegisterData',
            deviceIdList: [this.devicemsg.deviceId],
            attrs: {
                deviceSlaveSn: this.editRegisterForm.slaveSn,
                register: this.editRegisterForm.register,
                registerVal: this.value2
            }
        };
         device_cmd(para).then((res) => {
              this.begCode(res.code,res.message);
            if(res.code==0){
                this.$message({
                    message: '下发命令成功',
                    type: 'success'
                });
            }
        });
      })
    },
    scade1(index, row) {
      console.log(index)
      console.log(row)
        let para = {
            code: 'writeRegisterData',
            deviceIdList: [this.devicemsg.deviceId],
            attrs: {
                deviceSlaveSn: row.slaveSn,
                register: row.register,
                registerVal: row.registerVal,
                deviceType: 1
            }
        };
        this.loading = true;
        device_cmd(para).then((res) => {
              this.begCode(res.code,res.message);
            if(res.code==0){
                this.$message({
                    message: '下发命令成功',
                    type: 'success'
                });
            }
        });
    },
    scade2(index, row) {
        let para = {
            code: 'getRegisterData',
            deviceIdList: [this.devicemsg.deviceId],
            attrs: {
                deviceSlaveSn: row.slaveSn,
                registerFirstAddr: row.register,
                count: 1
            }
        };
        console.log(para)
        this.loading = true;
        //NProgress.start();
        device_cmd(para).then((res) => {
              this.begCode(res.code,res.message);
            this.$message({
                message: '下发命令成功',
                type: 'success'
            });
        });
    },
    oriModeCmd(val){//原模式
      let para = {
          code: 'writeRegisterData',//固定的，写数据点。
          deviceIdList: [this.devicemsg.deviceId],//设备Id数组
          attrs: {
              deviceSlaveSn: this.devicemsg.deviceSlave.slaveSn,//从机地址
              register: this.oriModelist.register,//数据点地址，
              registerVal: JSON.stringify(val),  //写的值，如果是开关型，0为关，1为开。
              deviceType: 1
          }
        }
      // console.log(para)
      device_cmd(para).then(res => {
          if(res.code == 0){
            this.$message({
                message: '下发命令成功',
                type: 'success'
            });
          }
        })
    },
    runModeCmd(val){//运行模式
      let para = {
          code: 'writeRegisterData',//固定的，写数据点。
          deviceIdList: [this.devicemsg.deviceId],//设备Id数组
          attrs: {
              deviceSlaveSn: this.devicemsg.deviceSlave.slaveSn,//从机地址
              register: this.runModelist.register,//数据点地址，
              registerVal: JSON.stringify(val), //写的值，如果是开关型，0为关，1为开。
              deviceType: 1
          }
        }
      // console.log(para)
      device_cmd(para).then(res => {
          if(res.code == 0){
            this.$message({
                message: '下发命令成功',
                type: 'success'
            });
          }
        })
    },
    devicegroup(){//群控
    // console.log(this.runModelist)
      // if(this.devicemodelgroup == 0){
        for(let i in this.deviceQuery){
          this.devicemsg = this.deviceQuery[i]
          if(this.devicemodelgroup == 0){
            // this.oriModeCmd(1)
            this.runModeCmd(0) 
          }else{
            // this.oriModeCmd(0)
            this.runModeCmd(1) 
          }
        }
        this.getlist()
      // }else{
      //   for(let i in this.deviceQuery){
      //     this.devicemsg = this.deviceQuery[i]
      //     this.oriModeCmd(0)
      //     this.runModeCmd(1) 
      //   }
      // }
    },
    changedevicemodel(){
      console.log(this.devicemodel)
      console.log(this.runModelist)
      console.log(this.oriModelist)
      //0为原模式，1为优化模式，当原模式registerVal为1，优化模式registerVal为0
      if(this.devicemodel == 0){
        // this.oriModeCmd(1)
        this.runModeCmd(0)   
      }else{
        // this.oriModeCmd(0)
        this.runModeCmd(1)  
      }
      this.getlist()
    },
    showalldevice(){
      let width1 = Math.floor(this.deviceQuery.length/4)
      console.log(width1)
      this.devicewidth = width1*34+34 + 'px'
      this.devicebackground = 'rgb(238, 238, 238)'
      this.hidedevice = true
    },
    hidelldevice(){
      this.devicewidth = 72 +'px'
      this.devicebackground = ''
      this.hidedevice = false
    },
    changedevice(index){
      this.deviceIndex = index
      this.hande_device_list = this.deviceQuery[index].deviceRecipeBodyVos
      this.devicemsg = this.deviceQuery[index]
      let runmode = this.hande_device_list.find((item) => {
        return item.remark == 'runMode'
      })
      if(runmode){
        this.runModelist = runmode
      }else{
        this.runModelist = ''
      }
      // console.log(runmode)
      let backTmp = this.hande_device_list.find((item) => {
        return item.remark == 'backTmp'
      })
      if(backTmp){
        this.backTmplist = backTmp
      }else{
        this.backTmplist = ''
      }
      let oriMode = this.hande_device_list.find((item) => {
        return item.remark == 'oriMode'
      })
      if(oriMode){
        this.oriModelist = oriMode
      }else{
        this.oriModelist = ''
      }
      let curEnergy = this.hande_device_list.find((item) => {
        return item.remark == 'curEnergy'
      })
      if(curEnergy){
        this.curEnerglist = curEnergy
      }else{
        this.curEnerglist = ''
      }
      // for(let i in this.hande_device_list){
      //   if(this.hande_device_list[i].remark == 'runMode'){
      //     this.runModelist = this.hande_device_list[i]
      //   }
      // }
      // for(let i in this.hande_device_list){
      //   if(this.hande_device_list[i].remark == 'oriMode'){
      //     this.oriModelist = this.hande_device_list[i]
      //   }
      // }
      // for(let i in this.hande_device_list){
      //   if(this.hande_device_list[i].remark == 'backTmp'){
      //     this.backTmplist = this.hande_device_list[i]
      //   }
      // }
      // for(let i in this.hande_device_list){
      //   if(this.hande_device_list[i].remark == 'curEnergy'){
      //     this.curEnerglist = this.hande_device_list[i]
      //   }
      // }
      console.log(this.curEnerglist)
      if(this.runModelist.registerVal == '0'){
        this.devicemodel = 0
      }else if(this.runModelist.registerVal == '1'){
        this.devicemodel = 1
      }
      if(this.oriModelist.registerVal == '0'){
        this.orimodel = 0
      }else if(this.oriModelist.registerVal == '1'){
        this.orimodel = 1
      }
      console.log(this.hande_device_list)
    },
    handleChange(value, direction, movedKeys){
      // console.log(value)
      // console.log(direction)
      // console.log(movedKeys)
      if(direction == 'left'){
        console.log(this.deviceGroupId)
        for(let i in movedKeys){
          let para = {
            deviceId: movedKeys[i],
            deviceGroupId: this.deviceGroupId
          };
          device_company_group_delete(para).then(res => {
            if (res.code == 0) {
              // this.$message({
              //   message: "移除成功",
              //   type: "success"
              // });
              this.getlist(this.deviceGroupId);
            }
          });
        }
        
      }
    },
    indexMethod(index) {
				let num = (this.page - 1) * 10 + index + 1;
				return num;
			},
    renderContent(h, { node, data, store }) {
      if(this.rendbool){
return (
        <span style="width:100%;">
          <span>
            <span>{node.label}</span>
          </span>
          <span v-if="{rendbool}" style="float: right; margin-right: 20px">
            <i
              class="el-icon-circle-plus-outline"
              on-click={($event) => this.handleAdd(store, data,$event)}
              title="添加"
            ></i>
            <i
              class="el-icon-edit"
              title="编辑"
              on-click={($event) => this.handleEdit(store, data,$event)}
            ></i>
            <i
              class="el-icon-delete"
              on-click={($event) => this.batchRemove(store, data,$event)}
              title="删除"
            ></i>
          </span>
        </span>
      );
      }else{
        return (
        <span style="width:100%;">
          <span>
            <span>{node.label}</span>
          </span>
  
        </span>
      );
      }
      
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getlist();
    },
    addshow() {
      if (!this.deviceGroupId) {
        this.$message({
          message: "请选择分组",
          type: "error"
        });
      } else {
        this.deviceVisible = true;
      }
    },
    //获取设备列表
    deviceSb() {
      console.log(this.binddata);
      console.log(this.deviceGroupId);
      let num = "";
      for (let i in this.binddata) {
        if (i == this.binddata.length - 1) {
          num = num + this.binddata[i];
        } else {
          num = num + this.binddata[i] + ",";
        }
      }
      let para = {
        deviceGroupId: this.deviceGroupId,
        ids: num
      };
      //NProgress.start();
      device_company_group_add(para).then(res => {
        this.begCode(res.code, res.message);
        this.$message({
          message: "绑定成功",
          type: "success"
        });
        this.getlist(this.deviceGroupId);
        this.deviceVisible = false;
        //NProgress.done();
      });
    },
    getlists(s, d, t){
      console.log(s)
      // if(s.childrens)
      if(s.childrens!=null && s.childrens.length!=0){
        this.$message({
          message: "该分组不是最小分组",
          type: "warning"
        });
        return false
      }
      this.textname=s.name;
      sessionStorage.setItem('showlistId',s.parentId)
      sessionStorage.setItem('groupList',JSON.stringify(s))
      console.log(s);
      console.log(d);
      console.log(t);
      this.deviceGroupId = s.id;
      let _this = this
      if(this.devicerecipeId){
        this.refresh = setInterval(()=>{
          _this.getlist();
        },5000)  
      }
    },
    getlist(s, d, t) {
      // this.runModelist = ''
      // this.oriModelist = ''
      // this.backTmplist = ''
      // this.curEnerglist = ''
      let para = {
        deviceGroupId: this.deviceGroupId,
        deviceDataRecipeId: this.devicerecipeId,
        pageNo: this.page,
        pageSize: this.pageSize,
      };
      // this.listLoading = true;
      device_company_group_query_slave(para).then(res =>{
        this.begCode(res.code, res.message);
        console.log(res)
        console.log(this.deviceIndex)
        if(res.code == 0){
          if(res.data.list){
          this.deviceQuery = res.data.list;
          if(this.deviceIndex == 0){
          this.devicemsg = res.data.list[0] //对应的从机
          this.hande_device_list = res.data.list[0].deviceRecipeBodyVos//从机对应的数据点
          }else{
          this.devicemsg = res.data.list[this.deviceIndex] //对应的从机
          this.hande_device_list = res.data.list[this.deviceIndex].deviceRecipeBodyVos//从机对应的数据点
          }
          console.log(this.hande_device_list)
          let runmode = this.hande_device_list.find((item) => {
            return item.remark == 'runMode'
          })
          if(runmode){
            this.runModelist = runmode
          }else{
            this.runModelist = ''
          }
          // console.log(runmode)
          let backTmp = this.hande_device_list.find((item) => {
            return item.remark == 'backTmp'
          })
          if(backTmp){
            this.backTmplist = backTmp
          }else{
            this.backTmplist = ''
          }
          let oriMode = this.hande_device_list.find((item) => {
            return item.remark == 'oriMode'
          })
          if(oriMode){
            this.oriModelist = oriMode
          }else{
            this.oriModelist = ''
          }
          let curEnergy = this.hande_device_list.find((item) => {
            return item.remark == 'curEnergy'
          })
          if(curEnergy){
            this.curEnerglist = curEnergy
          }else{
            this.curEnerglist = ''
          }
          console.log(this.runModelist)
          if(this.runModelist.registerVal == '0'){
            this.devicemodel = 0
          }else if(this.runModelist.registerVal == '1'){
            this.devicemodel = 1
          }
          if(this.oriModelist.registerVal == '0'){
            this.orimodel = 0
          }else if(this.oriModelist.registerVal == '1'){
            this.orimodel = 1
          }
          // for(let i in this.hande_device_list){
          //   if(this.hande_device_list[i].remark == 'runMode'){
          //     this.runModelist = this.hande_device_list[i]
          //   }
          // }
          // for(let i in this.hande_device_list){
          //   if(this.hande_device_list[i].remark == 'oriMode'){
          //     this.oriModelist = this.hande_device_list[i]
          //   }
          // }
          // for(let i in this.hande_device_list){
          //   if(this.hande_device_list[i].remark == 'backTmp'){
          //     this.backTmplist = this.hande_device_list[i]
          //   }
          // }
          // for(let i in this.hande_device_list){
          //   if(this.hande_device_list[i].remark == 'curEnergy'){
          //     this.curEnerglist = this.hande_device_list[i]
          //   }
          // }
          this.page = res.data.pageNo;
          this.total = res.data.totalCount;
          }
          this.listLoading = false;
        }
        
      })
      console.log(this.deviceQuery)
        let bindArr = []
         = [];
        for (let i in this.deviceQuery) {
          bindArr.push(this.deviceQuery[i].deviceId);
        }
        // es6数组去重
        this.binddata = Array.from(new Set(bindArr));
        // console.log(this.binddata)
      // device_company_group_query(para).then(res => {
      //   // this.begCode(res.code, res.message);
      //   // this.deviceQuery = res.data.list;
      //   //   this.page = res.data.pageNo;
          
      //   // this.total = res.data.totalCount;
      //   this.binddata = [];
      //   for (let i in this.deviceQuery) {
      //     this.binddata.push(this.deviceQuery[i].deviceId);
      //   }
      //   // this.listLoading = false;
      // });
    },
    getUsers2() {
      let para = {
        pageNo: 1,
        pageSize: 1000,
        name: this.filters.name,
        deviceTypeId: this.filters.deviceTypeId,
        deviceSn: this.filters.deviceSn,
        deviceModelId: this.filters.deviceModelId,
        terminalUser: this.filters.terminalUser,
        guild: this.filters.guild,
        area: this.filters.area1,
        address: this.filters.address,
        orderSn: this.filters.orderSn,
        companyId: this.scade1s,
        deviceUserId: this.scades
      };
      // localStorage.setItem("maplist", JSON.stringify(para));
      this.editLoading = true;
      //NProgress.start();
      device_query(para).then(res => {
        this.begCode(res.code, res.message);
        this.datalist = [];
        for (let i in res.data.list) {
          this.datalist.push({
            key: res.data.list[i].deviceId,
            label: res.data.list[i].name
          });
        }

        this.editLoading = false;
        console.log(this.users);
        //NProgress.done();
      });
    },
    getUsers() {
      let para = {
        pageNo: this.page,
        pageSize: 1000,
        name: this.filters.name
      };
      this.listLoading = true;
      //NProgress.start();
      device_group_query(para).then(res => { 
        this.begCode(res.code);
        // this.total = res.data.totalCount;
        if(sessionStorage.getItem('showlistId')){
          this.openGroup = sessionStorage.getItem('showlistId')
        }
        this.query = res.data;
        this.querys = [{ id: 0, name: "默认" }];
        this.getrecursion(res.data);
        this.listLoading = false;     
        //NProgress.done();
      });
    },
    getrecursion(data) {
      for (var i in data) {
        this.querys.push(data[i]);
        OUT:
        if (!data[i].childrens) {
          break OUT;
        } else {
          this.getrecursion(data[i].childrens);
        }
      }
      console.log(this.querys)
    },
    //删除
    handleDel: function(index, row) {
      this.$confirm("确认移除吗?", "提示", {
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          //NProgress.start();
          let para = {
            deviceId:row.deviceId,
            deviceGroupId:this.deviceGroupId
          };
          device_company_group_delete(para).then(res => {
            this.begCode(res.code);
            if (res.code == 0) {
              this.listLoading = false;
              //NProgress.done();
              this.$message({
                message: "移除成功",
                type: "success"
              });
              this.getlist(this.deviceGroupId);
            }
          });
        })
        .catch(() => {});
    },
    //显示编辑界面
    handleEdit: function(index, row,event) {
      event.stopPropagation()
      this.editFormVisible = true;
      this.editshow = row.id;
      this.editForm = Object.assign({}, row);
      this.filters.name = ''
      this.openGroup = row.id
      console.log(this.openGroup)
    },
    //显示新增界面
    handleAdd: function(store, data,event) {
      // console.log(event);
      console.log(store);
      console.log(data);
      if(event){
        event.stopPropagation()
      }
      this.addFormVisible = true;
      this.addForm = {
        name: "",
        parentId: data.id,
        priority: "",
        remark: ""
      };
      this.openGroup = data.id
      console.log(this.openGroup)
    },
    //编辑
    editSubmit: function() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);

            device_group_put(para).then(res => {
              this.begCode(res.code);

              if (res.code == 0) {
                this.editLoading = false;
                //NProgress.done();
                this.$message({
                  message: "提交成功",
                  type: "success"
                });
                this.$refs["editForm"].resetFields();
                this.editFormVisible = false;
                this.getUsers();
              }
            });
          });
        }
      });
    },
    //新增
    addSubmit: function() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.addForm);

            device_group_post(para).then(res => {
              this.begCode(res.code);
              if(res.code == 0){
                this.addLoading = false;
                //NProgress.done();
                this.$message({
                  message: "提交成功",
                  type: "success"
                });
                this.$refs["addForm"].resetFields();
                this.addFormVisible = false;
                this.getUsers();
              }else{
                 this.addLoading = false;
                  //NProgress.done();
                  this.$message({
                    message: res.message,
                    type: "warning"
                  });
                  this.$refs["addForm"].resetFields();
                  this.addFormVisible = false;
                  this.getUsers();
              }
            });
          });
        }
      });
    },
    selsChange: function(sels) {
      console.log(sels)
      this.sels = sels;
    },
    //删除
    batchRemove: function(s,d,event) {
      event.stopPropagation()
      this.openGroup = d.parentId
      var ids = this.sels.map(item => item.id).toString();
      this.$confirm("确认删除选中分组吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          //NProgress.start();
          let para = {
            idList: [d.id]
          };
          device_group_delete(para).then(res => {
            this.begCode(res.code);
            this.listLoading = false;
            //NProgress.done();
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getUsers();
          });
        })
        .catch(() => {});
    },
    details: function(index, row) {
      sessionStorage.setItem("facility_details", row.deviceId);
      this.$router.push({
        path: "/devices/deviceDatail"
      });
    },
    //告警开关
    alertSwitch(index,row){
      console.log(row.alarmStatus);
         let para = {
            alarmStatus: row.alarmStatus,
            deviceId: row.deviceId
          };
          device_device_alarm(para).then(res => {
            this.begCode(res.code, res.message);
            this.listLoading = false;
            //NProgress.done();
            this.$message({ 
              message: "修改成功",
              type: "success"
            });
          });
    },
    alarmSubmit(){
      var ids = this.sels.map(item => item.deviceId).toString();
      this.dellist = ids.split(",");
      this.$confirm("确认提交吗?", "提示", {
        type: "warning"
      }).then(() => {
          // this.listLoading = true;
          //NProgress.start();
          let para = {
            idList: this.dellist,
            value: this.alarmbool
          };
          console.log(para)
          device_device_alarm_list(para).then(res => {
            this.begCode(res.code, res.message);
            //NProgress.done();
            if (res.code == 0) {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.getlist();
              this.alarmVisible = false;
            }
          });
        })
        .catch(() => {});
    },
    fromedit(index, row) {
        if (this.menubt.indexOf('/device/cmd') == -1) {
            this.$message({
                message: '您没有下发命令的权限',
                type: 'warning'
            });
            return false;
        }
        this.index=index;
        this.editRegisterVisible = true;
        this.editRegisterForm = row;
    },
    handlehisty: function (index, row) {
        console.log(row)
        console.log(this.datalist)
        let pointnameArr = []
        for(let i in this.datalist){
          for(let k in this.binddata){
            if(this.datalist[i].key === this.binddata[k]){
              pointnameArr.push(this.datalist[i].label)
            }
          }
        }
        console.log(pointnameArr)
        sessionStorage.setItem('pointid', row.slaveSn+'~'+row.register+'~'+row.deviceSlaveName);
        sessionStorage.setItem('pointslaveSn', row.slaveSn);
        sessionStorage.setItem('deviceDataRecipeId', row.deviceDataRecipeId);
        sessionStorage.setItem('pointname', pointnameArr[0]);
        sessionStorage.setItem('facility_details', row.deviceId)
        this.$router.push({
            path: "/devices/history"
        });
    },
  },
  mounted() {
    this.menubt = localStorage.getItem('menubt');
    this.momenttime = setInterval(() => {
      this.moment = new Date().toLocaleString('chinese',{hour12:false})
      console.log(this.moment)
    }, 1000);
    let para3 = {
      pageNo: 1,
      pageSize: 9999
    };
    device_data_recipe_query(para3).then(res => {
      console.log(res)
      if(res.code == 0){
        if(res.data.list){//保证列表不为空
          this.devicerecipe = res.data.list
          this.devicerecipeId = res.data.list[0].id
          this.getlist()
          this.getlists(res.data.list[0].id)
        }else{
          return
        }
        if(sessionStorage.getItem('groupList')){
          let deitleId = JSON.parse(sessionStorage.getItem('groupList'))
          console.log(deitleId)
          this.getlists(deitleId)
        }
      }
    })
    this.usertype = JSON.parse(sessionStorage.getItem("user")).type;
    this.getUsers();
    this.getUsers2();
    
    let para = {
      name: "industry",
      pageSize: 999,
      pageNo: 1
    };

    let parauser = {
      pageNo: 1,
      pageSize: 9999,
      type: 1
    };
    user_query(para).then(res => {
      this.begCode(res.code, res.message);
      this.userclist = res.data.list;
      // if (this.userclist[0]) {

      //     this.scade = this.userclist[0].userId;
      // }
      this.scade = this.userID;
      // this.select_scade();

      // this.scade1get();
    });
    user_query(parauser).then(res => {
      this.begCode(res.code, res.message);
      this.firmlist = res.data.list;
    });
    
    // this.getUsers1();
    this.t = setInterval(() => {
      // this.getUsers1();
    }, 10000);
    device_type_query(para).then(res => {
      this.begCode(res.code, res.message);
      this.typelist = res.data.list;
      //NProgress.done();
    });  
    //NProgress.start();
    terminal_user_query(para3).then(res => {
      this.begCode(res.code, res.message);
      this.terminal_list = res.data.list;
      //NProgress.done();
    });
    
  },
  destroyed(){
    console.log('我离开了这个页面')
    clearInterval(this.momenttime)
    clearInterval(this.refresh)
  }
};
</script>

<style scoped>
.el-tree{
  /* height: 500px; */
  height: 915px;
  overflow: scroll;
}
.el-tree-node__content {
  border-bottom: 1px dashed #ccc;
  padding-bottom: 3px;
  padding-top: 3px;
  cursor: inherit;
}
.el-tree-node__content i {
  cursor: pointer;
  margin-right: 10px;
}
.el-tree-node__expand-icon{
          position :absolute;
          right: 2%;
      }
.group-title{
  display: flex;
  justify-content: space-between;
  padding: 12px 10px;
  align-items: center;
}   
.pb-colorbg {
      display: inline-block;
      width: 17px;
      height: 17px;
      border-radius: 50%
  }
  .bg-green {
      background: green
  }

  .bg-red {
      background: red;
  }

  .bg-gray {
      background: #666;
  }
  .bg-wihte {
      background: #0099cc !important;
      color: #000 !important;
  }
  .col-bg{
    /* width: 85%; */
    height: 400px;
    /* border: 2px solid #0099cc; */
    /* border-radius: 60px; */
    /* padding: 40px 25px; */
    overflow-y: auto;
    /* margin-left: 80px; */
    box-shadow:none;
    border: none;
  }
  .col-bg::-webkit-scrollbar{
    display: none;
  }
  .device-formula-list{
    position: absolute;
    top: 70px;
    left: 50px;
    width: 30px;
    height: 275px;
    overflow: hidden;
    /* background: rgb(238, 238, 238); */
    z-index: 1;
  }
  .device-formula-list2{
    width: 72px;
    left: 12px;
  }
  .devicetitle{
    width: 20px;
    height: 57px;
    display: inline-block;
    padding: 3px 6px;
    border: 1px solid #000;
    border-radius: 10px;
    background: #fff;
    color: #000;
    cursor: pointer;
    overflow: hidden;
  }
  .loadmroe{
    position: absolute;
    width: 70px;
    height: 30px;
    background: #0099cc;
    left: 10px;
    top: 345px;
    text-align: center;
    font-size: 20px;
    cursor: pointer;
    border-radius: 10px;
    border: 1px solid #000;
  }
  .parameter{
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    /* top: -30px;
    left: 170px; */
    width: 180px;
    height: 60px;
    background: #fff;
    z-index: 2;
    border-radius: 35px;
    border: 1px solid #0099cc;
    font-size: 17px;
  }
  .color-blue{
    color: #0099cc;
    font-weight: bold;
  }
  
</style>